package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryAll() {
        List<ShopType> list = new ArrayList<>();
        List<String> range = stringRedisTemplate.opsForList().range(CACHE_ShopType_Key + "all", 0, -1);
        if (range != null) {
            for (String s: range) {
                ShopType shopType = JSONUtil.toBean(s, ShopType.class);
                if (shopType != null) {
                    list.add(shopType);
                }
            }
        }
        if (list.size() != 0) {
            return Result.ok(list);
        }
        List<ShopType> list1 = query().orderByAsc("sort").list();
        if (list1 == null) {
            return Result.fail("未查询到类别信息");
        }
        for (ShopType shopType : list1) {
            stringRedisTemplate.opsForList().rightPush(CACHE_ShopType_Key + "all", JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.expire(CACHE_ShopType_Key + "all", CACHE_ShopType_TTL, TimeUnit.MINUTES);
        return Result.ok(list1);
    }
}
